/**
 * 弹出层管理类
 * @Author: wangqingguo
 * @Date: 2017/5/3
 */
var WindowManager = (function ($) {
    /***
     * 打开window窗口
     * @param params
     */
    var openLayer = function (params) {
        var topWin = getTopWindow(window);//获取顶级父窗体
        var endFun = params.end;
        params.end = function () {
            removeLastLayerIndex();
            if (endFun != null && typeof endFun === 'function') {
                endFun();
            }

        };

        var index = topWin.layer.open(params);
        addLayer(index,params.data, params.callBack, endFun);
    };
    /***
     * 关闭window窗口
     */
    var closeLayer = function (params) {
        var topWin = getTopWindow(window);//获取顶级父窗体
        var index = topWin.layer.getFrameIndex(window.name);
        var layerInfo = getLayerInfo(index);
        if (params !== undefined && params.returnValue !== null && layerInfo !== null && layerInfo.callBack !== null && typeof layerInfo.callBack === "function") {
            layerInfo.callBack(params.returnValue);
        }
        topWin.layer.close(index);
    };
    /***
     * 移除最后一个窗体
     * @returns {callBack|*}
     */
    var removeLastLayerIndex = function () {
        var topWin = getTopWindow(window);
        var arrs = topWin["com.weitu.layer.manager"];
        if (arrs != null) {
            arrs.pop();
        }
    };
    /***
     * 获取顶层window窗体
     * @param win
     * @returns {*}
     */
    var getTopWindow = function (win) {
        if (win.top != null) {
            var w = win.top;
            if (w === win) {
                //alert("是一个");
                return w;
            } else {
                return getTopWindow(w);
            }
        }
    };
    /***
     * 添加窗体
     */
    var addLayer = function (index, data,callBackFun, endFun) {
        var topWin = getTopWindow(window);
        if (topWin["com.weitu.layer.manager"] == null) {
            topWin["com.weitu.layer.manager"] = [];
        }
        var wM = {};
        wM.index = index;
        wM.data = data;
        wM.callBack = callBackFun;
        wM.end = endFun;
        topWin["com.weitu.layer.manager"].push(wM);

    };
    /****
     * 获取窗体回调函数
     */
    var getLayerInfo = function (index) {
        var topWin = getTopWindow(window);
        var arrs = topWin["com.weitu.layer.manager"];
        for (var i = 0; i < arrs.length; i++) {
            var arr = arrs[i];
            if (arr.index == index) {
                return arr;
            }
        }
        return null;
    };
    /****
     * 获取参数
     */
    var getParams = function () {
        var topWin = getTopWindow(window);
        var index = topWin.layer.getFrameIndex(window.name);
        var layerInfo = getLayerInfo(index);
        return layerInfo.data;
    };

    return {
        openLayer: openLayer,
        closeLayer: closeLayer,
        getParams:getParams
    };
})(jQuery);